package cn.com.dhcc.turbo.web.controller.registry;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.turbo.entity.exch.GapInfo;
import cn.com.dhcc.turbo.entity.exch.GapOwnerConf;
import cn.com.dhcc.turbo.entity.exch.GapUserConf;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.service.exch.cmdata.GapInfoService;
import cn.com.dhcc.turbo.service.exch.cmdata.GapOwnerConfService;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;
import cn.com.dhcc.turbo.service.registry.GapUserConfService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;

/**
 * 网闸交换配置管理Controller
 * 
 * @日期：May 22, 2014 1:47:54 PM
 * @作者：蒋佩钊
 * @版权所有：东华软件
 * @版本：1.0
 */
@Controller
@RequestMapping("/gap")
@TurboMenu(belongToMenu=LEAF_MENU.GAP_CONFIG)
public class GapConfigController extends BaseController {
	
	private String root_code="000000";//根节点编码
	@SuppressWarnings("deprecation")
	Logger logger = Log.getExistLogger(LOGTYPE.SAI);

	@Autowired
	private BaseInfoService baseInfoService;
	
	@Autowired
	private NodeInfoService nodeInfoService;
	
	@Autowired
	private GapOwnerConfService gapOwnerConfService;
	
	@Autowired
	private GapUserConfService gapUserService;
	@Autowired
	private GapInfoService gapInfoService;
	
	/**
	 * 网闸权限配置页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/gap_config_list")
	public String list(Model model) {
		try {
			//获取当前节点信息
			NodeInfo localNode=baseInfoService.getCurrentNodeInfo();
			
			
			//初始化网闸默认配置
	        gapOwnerConfService.initGapConf();
	       List<GapUserConf> get_user_conf=gapUserService.list(new WhereCondition());
			//查找当前节点已经分配的记录
			List<GapOwnerConf> gap_owner_conf_list=gapOwnerConfService.getAllByOwner(localNode.getNodeCode());
			model.addAttribute("get_user_conf", get_user_conf);
			model.addAttribute("treeData",nodeInfoService.getRootCheckedNodeTree(false, true,gap_owner_conf_list));
			model.addAttribute("gap_owner_conf_list", gap_owner_conf_list);
			boolean hasGap =  NodeInfoParam.hasGap();
			model.addAttribute("hasGap", NodeInfoParam.hasGap());
			model.addAttribute("localNode", localNode);
			if(hasGap){
				model.addAttribute(VO_KEY, gapInfoService.getGapInfo());
			}
			return "registry/gap_config_list";
		} catch (ServiceException e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}

	/**
	 * 
	 * @param addCodes
	 * @param deleteCodes
	 * @return
	 */
	@RequestMapping(value = "/gap_config_update")
	@ResponseBody
	public String configGap(String addCodes[],String deleteCodes[]){
		NodeInfo localNode;
		Map<String,Object> result=new HashMap<String, Object>();
		try {
			//获取当前节点信息
			localNode = baseInfoService.getCurrentNodeInfo();
			//新增或删除
			gapOwnerConfService.updateGapOwnerConfig(addCodes, deleteCodes, localNode);
			result.put("result", 0);
			result.put("msg", "删除成功");
		} catch (ServiceException e) {
			logger.error("操作失败", e);
			result.put("result", 1);
			result.put("msg", "程序异常"+e);
		}
		return JsonUtil.toJson(result);
	}
	
	
	
	/**
	 * 
	 * @param addCodes
	 * @param deleteCodes
	 * @return
	 */
	@RequestMapping(value = "/gap_info_get")
	@ResponseBody
	public String getGapInfo(){
		GapInfo gap = null;
		try {
			gap = gapInfoService.getGapInfo();
		} catch (ServiceException e) {
			logger.error(e);
		}
		return JsonUtil.toJson(gap);
	}
	
	/**
	 * 
	 * @param addCodes
	 * @param deleteCodes
	 * @return
	 */
	@RequestMapping(value = "/gap_info_update")
	@ResponseBody
	public String getGapInfo(GapInfo gapInfo){
		if (gapInfo.getId()==null|| "".equals(gapInfo.getId())) {
			gapInfo.setId(UUIDGenerator.getUUID());
		}
		Map<String,Object> result=new HashMap<String, Object>();
		gapInfo.setmTime(new Date());
		try {
			gapInfoService.insertOrUpdate(gapInfo);
			result.put("result", 0);
			result.put("msg", "保存成功!");
		} catch (ServiceException e) {
			logger.error("操作失败", e);
			result.put("result", 1);
			result.put("msg", "程序异常"+e);
		}
	
		
		return JsonUtil.toJson(result);
	}
	/**
	 * 网闸权限配置保存
	 * @param nodecode 用户编码
	 */
	@RequestMapping(value = "/gap_config_delete")
	@ResponseBody
	public String configDelete(String[] ids){
		Map<String,Object> result=new HashMap<String, Object>();
		//String[] userids,String ownerCode
		//获取当前节点信息
		try {
			gapOwnerConfService.deleteBatchById(ids);
			result.put("result", 0);
			result.put("msg", "删除成功");
		} catch (ServiceException e) {
			logger.error("操作失败", e);
			result.put("result", 1);
			result.put("msg", "程序异常"+e);
		}
		return JsonUtil.toJson(result);
	}
	
	/**
	 * 构造ztree数据
	 * @param nodes
	 * @param localNode
	 * @param ownerConfs
	 * @return
	 * @throws ServiceException 
	 */
	@SuppressWarnings("unused")
	private String toZtreeData(List<NodeInfo> nodes,NodeInfo localNode,List<GapOwnerConf> ownerConfs) throws ServiceException{
		List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		NodeInfo root = baseInfoService.getNodeInfoByCode(root_code);
		if (nodes!=null && !nodes.isEmpty()) {
			for (NodeInfo node : nodes) {
				Map<String,Object> map=new HashMap<String, Object>();
				map.put("id", node.getId());
				map.put("name", node.getNodeName());
				map.put("code", node.getNodeCode());
				map.put("pId",node.getPid());
				map.put("open", true);
				/*if (root.getIsLocal().equals("1")) {
					map.put("icon","javascript:return _rs_image_path+\'/node01.png';");
				} else if (root.getPid().equals(localNode.getId())) {
					map.put("icon","javascript:return _rs_image_path+\'/node02.png';");
				}else{
					map.put("icon","javascript:return _rs_image_path+\'/node00.png';");
				}*/
				/*if (containProperty(ownerConfs,node.getNodeCode())) {//本节点是否已经添加到可用的
					map.put("chkDisabled", "true");
				}*/
				list.add(map);
			}
			
		}
		
		return JsonUtil.toJson(list);
	}
	
	/**
	 * 判断列表GapOwnerConf中的gapuser属性值是否等于value
	 * @param ownerConfs
	 * @param value
	 * @return
	 */
	@SuppressWarnings("unused")
	private boolean containProperty(List<GapOwnerConf> ownerConfs,String value){
		if (ownerConfs!=null && !ownerConfs.isEmpty()) {
			for (GapOwnerConf gapOwnerConf : ownerConfs) {
				if (value.equals(gapOwnerConf.getGapUser())) {
					return true;
				}
			}
		}
		return false;
	}
	
	
	/**
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/sys_service_info", method = RequestMethod.GET)
	public String add(Model model, String id) {
		try {
		} catch (Exception e) {
			logger.error("添加系统服务信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/sys_service_info";
	}

	/**
	 * 添加系统服务信息界面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/sys_service_info_add", method = RequestMethod.GET)
	public String add(Model model) {
		try {
			/*List<SysInfo> sysInfoList = sysInfoService.getsysInfo();
			model.addAttribute("sysInfoList", sysInfoList);*/
		} catch (Exception e) {
			logger.error("添加系统服务信息失败", e);
			return toAlertPage(model, e.getMessage());
		}
		return "registry/sys_service_info_add";
	}
	
	
}
